package com.kcht.itsed.mws.subscribescheduler.biz;

import com.kcht.itsed.mws.commmodel.SpecId;
import com.kcht.itsed.mws.subscribescheduler.facade.ISubscriberDeployer;
import com.kcht.itsed.mws.subscribescheduler.facade.ISubscriberLoader;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订阅者容器
 * @author 张文硕
 *
 */
@Component
public class CommonSubscribersContainer implements ISubscriberDeployer,ISubscriberLoader{

	private Map<SpecId,List<String>> subsContainer = new HashMap<>();	//订阅者们：key是规则，value是URL列表

	@PostConstruct
	void testcaseStartup(){
		deployEcSubscriber("xxx","http://asdfasdfadsfasfd/qwerqewrqwer");
	}
	
	
	@Override
	public synchronized void deployEcSubscriber(String ecSpecName, String subscriberUri) {
		SpecId sid = new SpecId("EC",ecSpecName);
		if(!subsContainer.containsKey(sid))subsContainer.put(sid, new ArrayList<String>());
		subsContainer.get(sid).add(subscriberUri);
	}

	@Override
	public synchronized void deployCcSubscriber(String ccSpecName, String subscriberUri) {
		SpecId sid = new SpecId("CC",ccSpecName);
		if(!subsContainer.containsKey(sid))subsContainer.put(sid, new ArrayList<String>());
		subsContainer.get(sid).add(subscriberUri);		
	}

	@Override
	public synchronized void undeployEcSubscriber(String ecSpecName, String subscriberUri) {
		SpecId sid = new SpecId("EC",ecSpecName);
		if(subsContainer.containsKey(sid))subsContainer.get(sid).remove(subscriberUri);
	}

	@Override
	public synchronized void undeployCcSubscriber(String ccSpecName, String subscriberUri) {
		subsContainer.get(new SpecId("CC",ccSpecName)).remove(subscriberUri);
	}

	@Override
	public synchronized List<String> loadSubscribersOfSpec(String specType, String specName) {
		List<String> subs = subsContainer.get(new SpecId(specType,specName));
		List<String> specSubs = new ArrayList<String>(subs.size());
		specSubs.addAll(subs);
		return specSubs;
	}
	
}
